<template>
  <div>
      <!-- 面包屑导航区 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
               <el-alert
                    title="注意:只允许为第三级分类设置相关参数!"
                    type="warning"
                    :closable ='false'
                    show-icon>
                </el-alert>
                <!-- 级联选择框 -->
                <el-row class="btn">
                    <el-col>
                       <span>选择商品分类 :</span>
                    <el-cascader
                            v-model="selectKeys"
                            :options="cateList"
                            :props="cateProps"
                            @change="handleChange"
                             clearable
                            >
                    </el-cascader>
                    </el-col>
                </el-row>

            <!-- tab页签 -->
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" :disabled ="this.selectKeys.length !== 3 ? true:false" @click="addParams">添加参数</el-button>
                    <!-- 表格 -->
                    <el-table :data="manyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="{row}">
                                 <el-tag type="success" closable v-for="(item,i) in row.attr_vals" :key="i" @close ='delTag(i,row)'>
                                 {{item}}
                                </el-tag>
                                <!-- tag标签的切换 -->

                            <el-input
                            class="input-new-tag"
                            v-if="row.inputVisible"
                            v-model="row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(row)"
                            @blur="handleInputConfirm(row)"
                            ></el-input>
                            <el-button v-else class="button-new-tag" 
                            size="small" @click="showInput(row)">+ New Tag</el-button>



                            </template>
                        </el-table-column>
                        <el-table-column type="index" width="50" label="#"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作" width="180px">
                            <template slot-scope="{row}">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="put(row.attr_id)">修改</el-button>
                                <el-button type="danger"  icon="el-icon-delete" size="mini" @click="delData(row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!--静态属性 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled ='isDisabled' @click="addShuxing">添加属性</el-button>
                      <!-- 表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="{row}">
                                 <el-tag type="success" closable v-for="(item,i) in row.attr_vals" :key="i" @close ='delTag(i,row)'>
                                 {{item}}
                                </el-tag>
                                <!-- tag标签的切换 -->

                            <el-input
                            class="input-new-tag"
                            v-if="row.inputVisible"
                            v-model="row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(row)"
                            @blur="handleInputConfirm(row)"
                            ></el-input>
                            <el-button v-else class="button-new-tag" 
                            size="small" @click="showInput(row)">+ New Tag</el-button>



                            </template>
                        </el-table-column>
                        <el-table-column type="index" width="50" label="#"></el-table-column>
                        <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                        <el-table-column label="操作" width="180px">
                            <template slot-scope="{row}">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="put(row.attr_id)">修改</el-button>
                                <el-button type="danger"  icon="el-icon-delete" size="mini" @click="delData(row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <!-- 添加动态参数和添加静态属性的弹框 -->
                 <el-dialog :title="this.activeName === 'many'? '添加动态参数' : '添加静态属性' " :visible.sync="dialogVisible" width="40%" @close="closeDialog">
                     
                       <el-form label-width="100px" :model ='addForm' :rules="rules" ref="addFormRef">
                            <el-form-item :label="addLabel" prop="attr_name">
                                <el-input v-model="addForm.attr_name" ></el-input>
                            </el-form-item>
                        </el-form>

                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="queding">确 定</el-button>
                    </span>
                </el-dialog>
            <!-- 修改动态参数和添加静态属性的弹框 -->
                 <el-dialog :title="this.activeName === 'many'? '修改动态参数' : '修改静态属性' " :visible.sync="putDialogVisible" width="40%" @close="putCloseDialog">
                       <el-form label-width="100px" :model ='putForm' :rules="puRrules" ref="putFormRef">
                            <el-form-item :label="addLabel" prop="attr_name">
                                <el-input v-model="putForm.attr_name" ></el-input>
                            </el-form-item>
                        </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="putDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="putQueDing">确 定</el-button>
                    </span>
                </el-dialog>
        </el-card>
  </div>
</template>

<script>
export default {
  name:'paramsIndex',
  components: {},
  props: {},
  data() {
    return {
        cateList:[], //级联选择框的数据,
        selectKeys:[],
        cateProps:{
           value:'cat_id',
           label:'cat_name',
           children:'children',
           expandTrigger: 'hover',
           checkStrictly: true 
        },
        activeName:'many',
        manyTableData:[],
        onlyTableData:[],
        dialogVisible:false,
        addForm:{
            attr_name:''
        },
        rules:{
           attr_name:[
                 { required: true, message: '请输入名称', trigger: 'blur' },
                ],
        },
        // 修改对话对话框的数据
         putDialogVisible:false,
         putForm:{
            attr_name:''
        },
        puRrules:{
            attr_name:[
                 { required: true, message: '请输入名称', trigger: 'blur' },
                ],
        },
    }
  },
  created() {
    this.getCateList()
  },
  computed:{
        isDisabled(){
            if(this.selectKeys.length !== 3) {
                return true
            }else{
                return false
            }
        },
        addLabel(){
            return this.activeName === 'many'?'动态参数':'静态属性'
        },
        fenId(){
            return this.selectKeys[this.selectKeys.length - 1]
        }
  },
  methods: {
   async getCateList(){
      const {data:res} =  await this.$http.get('/categories')
      if(res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.cateList = res.data
    },
   async handleChange(){
               this.sameFn()
         //控制选择器只能选择第三级 只需判断selectKeysd的长度是不是等于三,若不是直接清空数组
        //  if(this.selectKeys.length !== 3){
        //     return this.selectKeys = []
        //  }
         //如果选择的是第三级
    //    const {data:res}  =await this.$http.get(`/categories/${this.selectKeys[this.selectKeys.length - 1]}/attributes`,{
    //     params:{sel:this.activeName}
    //    })
    //    if(res.meta.status !== 200) return this.$message.error('获取数据失败')
    //      this.$message.success('获取数据成功')
    },
    handleClick(){
         this.sameFn()
    },
    //级联选择器和 tab页签 改变都应改发起请求 所以封装一个公共方法
     async sameFn(){
          //控制选择器只能选择第三级 只需判断selectKeysd的长度是不是等于三,若不是直接清空数组
         if(this.selectKeys.length !== 3){
           this.selectKeys = []
           this.manyTableData = []
           this.onlyTableData = []
           return
         }
         //如果选择的是第三级
       const {data:res} = await this.$http.get(`/categories/${this.selectKeys[this.selectKeys.length - 1]}/attributes`,{
        params:{sel:this.activeName}
       })
        //渲染展开行里面的数据
           res.data.forEach(v => {
            v.attr_vals = v.attr_vals ? v.attr_vals.split(' ') : []
            this.$set(v,'inputVisible' ,false)
            this.$set(v,'inputValue','')
           })
          console.log(res.data);


       if(res.meta.status !== 200) return this.$message.error('获取数据失败')
         //数据存储 如果是many请求的 存到manyTableData 如果是only获取的 存到onlyTableData
         if(this.activeName === 'many'){
                 this.manyTableData = res.data
         }else{
             this.onlyTableData = res.data
         }
     },
      addParams(){
        this.dialogVisible = true
      },
      addShuxing(){
        this.dialogVisible = true
      },
      closeDialog(){
        console.log(this.$refs.addFormRef);
         this.$refs.addFormRef.resetFields()
      },
      queding(){
          this.$refs.addFormRef.validate(async isok => {
             if(!isok) return
           const {data:res} =  await this.$http.post(`categories/${this.fenId}/attributes`,{
            attr_name:this.addForm.attr_name,
            attr_sel:this.activeName
           })
           if(res.meta.status !== 201) return this.$message.error('添加失败')
           this.dialogVisible = false
          })
      },
    async  put(id){
        const {data:res} = await  this.$http.get(`categories/${this.fenId}/attributes/${id}`,{
            params:{attr_sel:this.activeName}
           })
           this.putForm = res.data
         this.putDialogVisible  = true
      },
      putCloseDialog(){
        this.$refs.putFormRef.resetFields()
      },
      putQueDing(){
          this.$refs.putFormRef.validate( async isok => {
            if(!isok) return this.$message.error('信息有误')
             const {data:res} =await this.$http.put(`categories/${this.fenId}/attributes/${this.putForm.attr_id}`,{
                attr_sel:this.activeName,
                attr_name:this.putForm. attr_name
             })
             if(res.meta.status !== 200) this.$message.error('修改数据失败')
               this.$message.success('修改数据成功')
                this.putDialogVisible = false
              this.sameFn()
          
          })  
             
      },
     async delData(id){
          const {data:res} =await this.$http.delete(`categories/${this.fenId}/attributes/${id}`)
           if(res.meta.status !== 200) this.$message.error('删除数据失败')
               this.$message.success('删除数据成功')
                this.sameFn()
      },
     async handleInputConfirm(row){
        if(row.inputValue.trim().length === 0){
            //说明输入的内容不合法
            row.inputValue = ''
            row.inputVisible = false
            return
        }else{
            row.attr_vals.push(row.inputValue)
           const{data:res} = await this.$http.put(`categories/${this.fenId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            if(res.meta.status !== 200) this.$message.error('修改参数项失败')
               this.$message.success('修改参数项成功')
                row.inputValue = ''
                row.inputVisible = false
        }
        
      },
      showInput(row){
       row.inputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
     async delTag(i,row){
        //把要删除的项先从数组里删除
           row.attr_vals.splice(i,1)
           const{data:res} = await this.$http.put(`categories/${this.fenId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            if(res.meta.status !== 200) this.$message.error('修改参数项失败')
               this.$message.success('修改参数项成功')
      }
  }
};
</script>
<style scoped lang='less'>
.el-breadcrumb{
    margin-bottom: 15px;
}
.btn{
    margin: 15px 0px;
}
.el-table{
    margin-top: 15px;
}
.el-tag {
    margin: 10px;
}
.input-new-tag{
    width: 150px;
}
</style>